package com.dgut.smart_house.service.impl;

import com.dgut.smart_house.domain.DatasForKeyCard;
import com.dgut.smart_house.domain.Device;
import com.dgut.smart_house.domain.KeyCard;
import com.dgut.smart_house.mapper.DeviceMapper;
import com.dgut.smart_house.mapper.KeyCardMapper;
import com.dgut.smart_house.service.KeyCardService;
import com.dgut.smart_house.withHardware.SocketCompent;
import com.dgut.smart_house.withHardware.WithHardwareSocket;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class KeyCardServiceImpl implements KeyCardService {

    @Autowired
    private KeyCardMapper keyCardMapper;

    @Autowired
    private SocketCompent socketCompent;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private AsyncService asyncService;

    static public final String CreateNewCardCommand="0x12";
    static public final String DeleteNewCardCommand="0x61";
    static public final int KeyDoorTypeId=6;


    @Override
    public KeyCard findCardByKey(int keyId) {
        return keyCardMapper.findCardByKey(keyId);
    }

    @Override
    public List<KeyCard> findAllCard(int fromUser) {
        return keyCardMapper.findAllCard(fromUser);
    }

    @Override
    public Integer createCardMaster(KeyCard keyCard) {
        Device device=deviceMapper.findKeyDoor(KeyDoorTypeId,keyCard.getFromUser());
        socketCompent.getHardwareSocket().sendMsg(CreateNewCardCommand);
        asyncService.asynCreateCardMethod(keyCard,device);
        return keyCardMapper.createCardMaster(keyCard);
    }

    @Override
    public Integer deleteCardMaster(int keyId) {
        KeyCard keyCard=keyCardMapper.findCardByKey(keyId);
        Device device=deviceMapper.findKeyDoor(6,keyCard.getFromUser());
        String string="0x"+Long.toHexString(keyCard.getCardId());
        socketCompent.getHardwareSocket().sendMsg(DeleteNewCardCommand+":"+string);
        return keyCardMapper.deleteCardMaster(keyId);
    }

    @Override
    public Integer updateCardMaster(String cardDesc,int keyId) {
        return keyCardMapper.updateCardMaster(cardDesc,keyId);
    }

    @Override
    public int createData(KeyCard keyCard) {
        return keyCardMapper.createData(keyCard);
    }

    @Override
    public PageInfo findAllCardLog(int fromUser,int pageNo,int pageSize) {

        PageHelper.startPage(pageNo, pageSize);
        List<DatasForKeyCard> keyCards = keyCardMapper.findAllCardLog(fromUser);
        PageInfo<DatasForKeyCard> page = new PageInfo<DatasForKeyCard>(keyCards);

        return page;
    }
}
